
package com.putao.album.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.putao.album.R;
import com.putao.album.dialog.bean.RequestPhotoTag;
import com.putao.album.eventbus.BasePostEvent;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.HttpRequestUtil;
import com.putao.album.util.Loger;
import com.putao.album.util.PuTaoConstants;
import com.putao.album.util.StringHelper;
import com.putao.album.widget.pttag.PostTag;
import com.putao.album.widget.pttag.PtTag;
import com.putao.album.widget.pttag.PtTagListView;
import com.putao.album.widget.pttag.PtTagView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by chen on 15/5/14.
 */
public class PhotoTagManagerDialog extends Dialog {
    private PtTagListView mTagListView;

    protected PhotoTagManagerDialog(Context context) {
        super(context);
    }

    protected PhotoTagManagerDialog(Context context, int theme) {
        super(context, theme);
    }

    protected PhotoTagManagerDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    public interface TagAddListener {
        public void success(List<PtTag> tags);
    }

    public static class Builder {
        private final List<PtTag> mExistTags = new ArrayList<PtTag>();
        private final List<PtTag> mAllTags = new ArrayList<PtTag>();
        private Context context;
        private String positiveButtonText;
        private String negativeButtonText;
        private OnClickListener negativeButtonClickListener;
        private TagAddListener addListener;
        private PtTagListView exist_tag_view, all_tag_view;
        private EditText etx_tag;

        public Builder(Context context) {
            this.context = context;
        }

        public Builder setNegativeButton(OnClickListener listener) {
            this.negativeButtonClickListener = listener;
            return this;
        }

        public Builder setTagAddSuccessListener(TagAddListener listener) {
            this.addListener = listener;
            return this;
        }

        public Builder setPositiveButton(int positiveButtonText, OnClickListener listener) {
            this.positiveButtonText = (String) context.getText(positiveButtonText);
            return this;
        }

        public Builder setPositiveButton(String positiveButtonText, OnClickListener listener) {
            this.positiveButtonText = positiveButtonText;
            return this;
        }

        public Builder setNegativeButton(int negativeButtonText, OnClickListener listener) {
            this.negativeButtonText = (String) context.getText(negativeButtonText);
            this.negativeButtonClickListener = listener;
            return this;
        }

        public Builder setNegativeButton(String negativeButtonText, OnClickListener listener) {
            this.negativeButtonText = negativeButtonText;
            this.negativeButtonClickListener = listener;
            return this;
        }

        String photo_id;

        public PhotoTagManagerDialog Create(String photo_id) {
            this.photo_id = photo_id;
            LayoutInflater inflater = LayoutInflater.from(context);
            final PhotoTagManagerDialog dialog = new PhotoTagManagerDialog(context, R.style.pt_dialog_style);
            dialog.setCanceledOnTouchOutside(false);
            View layout = inflater.inflate(R.layout.dialog_pt_tag_manager_layout, null);
            dialog.setContentView(layout);
            Button positiveButton = (Button) layout.findViewById(R.id.positiveButton);
            Button negativeButton = (Button) layout.findViewById(R.id.negativeButton);
            etx_tag = (EditText) layout.findViewById(R.id.etx_tag);
            etx_tag.setOnEditorActionListener(
                    new TextView.OnEditorActionListener() {
                        @Override
                        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                            if (actionId == EditorInfo.IME_ACTION_DONE) {
                                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(
                                        Context.INPUT_METHOD_SERVICE);
                                if (imm.isActive()) {
                                    imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                                }
                                String value = etx_tag.getText().toString();
                                if(!StringHelper.isEmpty(value)){
                                    PtTag tag = new PtTag();
                                    tag.setTitle(value);
                                    exist_tag_view.addTag(tag);
                                    etx_tag.setText("");
                                }
                                return true;
                            } else {
                                return false;
                            }
                        }
                    }
            );
            positiveButton.setText(positiveButtonText);
            positiveButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    dialog.dismiss();
                    queryAddAlbumTag(dialog);
                }
            });
            negativeButton.setText(negativeButtonText);
            if (negativeButtonClickListener != null) {
                negativeButton.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        negativeButtonClickListener.onClick(dialog, DialogInterface.BUTTON_NEGATIVE);
                    }
                });
            }
            exist_tag_view = (PtTagListView) layout.findViewById(R.id.exist_tag_view);
            exist_tag_view.setTagViewBackgroundRes(R.drawable.tag_bg_tag);
            exist_tag_view.setDeleteMode(true);
            exist_tag_view.setOnTagClickListener(new PtTagListView.OnTagClickListener() {
                @Override
                public void onTagClick(PtTagView tagView, PtTag tag) {
                    //                    showTipDialog(tag);
                    if (tag.isDeleteEnable()) {
                        exist_tag_view.removeTag(tag);
                    }
                }
            });
            //            setUpData();
            all_tag_view = (PtTagListView) layout.findViewById(R.id.all_tag_view);
            all_tag_view.setTagViewTextColorRes(R.color.text_color_dark_888888);
            //            exist_tag_view.setTagViewBackgroundRes(R.drawable.tag_bg_tag);
            //            exist_tag_view.setDeleteMode(true);
            //            setUpData();
            all_tag_view.setOnTagClickListener(new PtTagListView.OnTagClickListener() {
                @Override
                public void onTagClick(PtTagView tagView, PtTag tag) {
                    if (exist_tag_view.getTags().size() >= 12) {
                        return;
                    }
                    for (int i = 0; i < exist_tag_view.getTags().size(); i++) {
                        if (tag.getTitle().equals(exist_tag_view.getTags().get(i).getTitle())) {
                            return;
                        }
                    }
                    exist_tag_view.addTag(tag);
                }
            });
            queryGetTagList();
            return dialog;
        }

        public void queryAddAlbumTag(final PhotoTagManagerDialog dialog) {
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("baby_id", CommonUtils.getBabyId());
            params.put("photo_id", photo_id);
            final List<PtTag> list = exist_tag_view.getTags();
            String value = etx_tag.getText().toString();
            String tags = "";
            if (!StringHelper.isEmpty(value)) {
                PtTag tag= new PtTag();
                tag.setTitle(value);
                list.add(tag);
            }
            for (int i = 0; i < list.size(); i++) {
                tags += list.get(i).getTitle() + ",";
            }

            List<PostTag> postTags = new ArrayList<PostTag>();
            for(int i=0;i<list.size();i++){
                PostTag item = new PostTag();
                item.setId(list.get(i).getId());
                item.setTag(list.get(i).getTitle());
                postTags.add(item);
            }
            Gson gson = new Gson();
            String reslut = gson.toJson(postTags);
            params.put("tag", reslut);
            if (list.size() < 1) {
                params.put("delete_all", "1");
            }
            HttpRequestUtil.doHttpPostRequest(context, PuTaoConstants.API_POST_Add_PHOTO_TAG,
                    new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)),
                    new HttpRequestUtil.RequestResponseListener() {
                        @Override
                        public void success(int statuscode, String response) {
                            if (addListener != null) {
                                addListener.success(list);
                            }
                            Bundle bundle = new Bundle();
                            EventBus.getDefault().post(new BasePostEvent(PuTaoConstants.EVENTBUS_ADD_TAG_SUCCESS, bundle));
                        }

                        @Override
                        public void failed(int statuscode, String response) {
                            Loger.d("response:::" + response);
                        }
                    });
        }

        public void queryGetTagList() {
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("baby_id", CommonUtils.getBabyId());
            params.put("photo_id", photo_id);
            HttpRequestUtil.doHttpGetRequest(context, PuTaoConstants.API_GET_PHOTO_TAG,
                    new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), true,
                    new HttpRequestUtil.RequestResponseListener() {
                        @Override
                        public void success(int statuscode, String response) {
                            //                            Loger.i("response:" + response);
                            final String is_owner = "1";
                            Gson gson = new Gson();
                            RequestPhotoTag mRequestPhotoTag = (RequestPhotoTag) gson.fromJson(response, RequestPhotoTag.class);
                            ArrayList<RequestPhotoTag.PhotoTag> albumTags = mRequestPhotoTag.data.photoTag;
                            ArrayList<RequestPhotoTag.Tag> commonTags = mRequestPhotoTag.data.commonTag;
                            for (int i = 0; i < albumTags.size(); i++) {
                                PtTag tag = new PtTag();
                                tag.setId(StringHelper.stringToInt(albumTags.get(i).id));
                                if (is_owner.equals(albumTags.get(i).is_owner)) {
                                    tag.setDeleteEnable(true);
                                } else {
                                    tag.setDeleteEnable(false);
                                }
                                tag.setTitle(albumTags.get(i).tag);
                                mExistTags.add(tag);
                            }
                            for (int i = 0; i < commonTags.size(); i++) {
                                PtTag tag = new PtTag();
                                tag.setChecked(true);
                                tag.setTitle(commonTags.get(i).tag);
                                mAllTags.add(tag);
                            }
                            exist_tag_view.setTags(mExistTags);
                            all_tag_view.setTags(mAllTags);
                        }

                        @Override
                        public void failed(int statuscode, String response) {
                            Loger.d("response:::" + response);
                        }
                    });
        }
    }
}
